<?php

namespace App\Http\Controllers\product;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Models\ProductClassBranch;
use App\Models\SystemBase;
use App\Models\Worker;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Http\Controllers\BranchUtils;
#产品分类表
use App\Models\ProductClass;
#产品表
use App\Models\Product;
#订单表
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use PhpParser\Node\Expr\Isset_;

//定义超全局变量(Redis过期时间)
#这里是产品的控制器
class ProductController extends Controller
{
    //产品分类的添加和修改
    public function ProductCateSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::where('id', $worker_id)->with('branchesManage')->first();
        if (empty($worker['branchesManage'])) {
            return LMReturn::Error('没有管理权限！');
        }
        try {
            $all = $request->all();
            if (isset($all['branch_list'])) {
                $bm_list = [];
                foreach ($all['branch_list'] as $branch_id) {
                    $abm_list = BranchUtils::getBranchChain($branch_id);
                    foreach ($abm_list as $a) {
                        if (!in_array($a, $bm_list)) {
                            $bm_list[] = $a;
                        }
                    }
                }
            } else {
                $bm_list = [];
                $branchs = Branch::all();
                foreach ($branchs as $branch) {
                    $bm_list[] = $branch['id'];
                }
            }
            if (isset($all['id'])) {
                $product_class = ProductClass::find($all['id']);
                $status_type = 1;
                $old_pid = $product_class->pid;
            } else {
                $product_class = new ProductClass();
                $status_type = 2;
                $old_pid = null;
            }
            $category_name = $all['category_name'];
            $pid = $all['pid'];
            if(isset($all['id'])) {
                if ($pid == $all['id']) {
                    return LMReturn::Error('不可将自己设置为父级分类');
                }
            }
            if ($pid != 0 && $pid != null) {
                $branch_id = $worker['branchesManage'][0]['id'];
                $classify_branch = ProductClassBranch::where('branch_id', $branch_id)->where('product_class_id', $pid)->first();
                if (empty($classify_branch)) {
                    return LMReturn::Error('没有该父级产品类型权限');
                }
            }
            if ($pid != 0) {
                $p_product_class = ProductClass::find($pid);
                if ($p_product_class) {
                    if ($p_product_class->pid != null && $p_product_class->pid != 0) {
                        return LMReturn::Error('该类型已是基础分类，无法添加子分类');
                    }
                }
            } else {
                $pid = null;
            }
            if (isset($all['max_money'])) {
                $max_money = $all['max_money'];
            } else {
                $max_money = 0;
            }
            $status = $all['status'] ?? '1';
            $app_status = $all['app_status'] ?? '1';
            $wx_xcx_status = $all['wx_xcx_status'] ?? '1';
            $pc_status = $all['pc_status'] ?? '1';
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误，错误代码PC001', 'PC001');
        }
        try {
            DB::beginTransaction(); //开启事务
            $product_class->max_money = $max_money;
            $product_class->category_name = $category_name;
            $product_class->pid = $pid;
            $product_class->status = $status;
            $product_list = $product_class->products;
            // dd($product_list);
            foreach ($product_list as $product) {
                $product->state = $status;
                $product->wx_xcx_status = $wx_xcx_status;
                $product->app_status = $app_status;
                $product->pc_status = $pc_status;
                $product->save();
            }
            $product_class->app_status = $app_status;
            $product_class->wx_xcx_status = $wx_xcx_status;
            $product_class->pc_status = $pc_status;
            $product_class->save();
            $product_class->branches()->sync($bm_list);
            if (isset($all['branch_list'])) {
                ProductClassBranch::where('product_class_id', $product_class->id)->update(['is_display' => 2]);
                ProductClassBranch::where('product_class_id', $product_class->id)->whereIn('branch_id', $all['branch_list'])->update(['is_display' => 1]);
            }
            if ($status_type == 1 && $old_pid != $pid) {
                $p_branch_list = utils::get_class_branch_list($pid);
                $branch_list = utils::get_class_branch_list($all['id']);
                foreach ($branch_list as $branch_id) {
                    if (!in_array($branch_id, $p_branch_list)) {
                        $old_class_branch = ProductClassBranch::where('branch_id', $branch_id)->where('product_class_id', $all['id'])->first();
                        $is_display = $old_class_branch->is_display;
                        $pcb = new ProductClassBranch();
                        $pcb->branch_id = $branch_id;
                        $pcb->product_class_id = $pid;
                        $pcb->is_display = $is_display;
                        $pcb->save();
                    }
                }
            }
            DB::commit(); //提交至数据库
            return LMReturn::Success($product_class);
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('添加修改出现错误，错误代码PC002', 'PC002');
        }
    }

    //商品分类列表(有树结构)
    public function ProductCateList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::where('id', $worker_id)->with('branches')->first();
        if (isset($worker['branches'])) {
            $branch_id = $worker['branches'][0]['id'];
        } else {
            return LMReturn::Success();
        }
        //接收前端传递过来的值
        $all = $request->all();
        $where = [];
        if (isset($all['app_status'])) {
            $app_status = $all['app_status'];
            $where[] = ['app_status', $app_status];
        }
        if (isset($all['wx_xcx_status'])) {
            $wx_xcx_status = $all['wx_xcx_status'];
            $where[] = ['wx_xcx_status', $wx_xcx_status];
        }
        if (isset($all['pc_status'])) {
            $pc_status = $all['pc_status'];
            $where[] = ['pc_status', $pc_status];
        }
        if (isset($all['status'])) {
            $state = $all['status'];
            $where[] = ['status', $state];
        }
        $info = json_decode(
            ProductClass::where($where)->whereHas('branches', function ($query) use ($branch_id) {
                $query->where('branch_id', $branch_id);
            })
                ->orderby("create_time", "desc")
                ->get(),
            true
        );
        $product_list = [];
        foreach ($info as $product) {
            $product_list[] = $product['id'];
        }
        $product_class_list = [];
        $product_class_dic = [];
        $product_class_id = null;
        $branch_class = ProductClassBranch::where('is_display', 1)->whereIn('product_class_id', $product_list)->get();
        if ($branch_class) {
            foreach ($branch_class as $branch) {
                if ($branch['product_class_id'] != $product_class_id) {
                    if ($product_class_list) {
                        $product_class_dic[$product_class_id] = $product_class_list;
                        $product_class_list = [];
                    }
                    $product_class_list[] = $branch['branch_id'];
                    $product_class_id = $branch['product_class_id'];
                } else {
                    $product_class_list[] = $branch['branch_id'];
                }
            }
            $product_class_dic[$product_class_id] = $product_class_list;
        }
        foreach ($info as $key => $value) {
            try {
                $info[$key]['branches'] = $product_class_dic[$value['id']];
                $info[$key]['create_time'] = date('Y-m-d', strtotime($value['create_time']));
            } catch (\Throwable $th) {
            }
        }
        return LMReturn::Success(CommonFun::ArrToTreeList($info, "id", "pid"));
    }

    //商品分类删除
    public function ProductCateDelete(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        //根据传递过来的的ID，进行查询产品表，如果说查询到了，那么就给出提示不能删除，反之就是可以进行删除的
        $info = json_decode(Product::where("class_id", $all['id'])->get(), true);
        //判断是否查询到了数据
        if (empty($info)) {
            //这里是没有查询到
            $info = json_decode(ProductClass::where("pid", $all['id'])->get(), true);
            if (empty($info)) {
                $res = ProductClass::where("id", $all['id'])->delete();
                ProductClassBranch::where('product_class_id', $all['id'])->delete();
                return LMReturn::sqlRes($res);
            } else {
                return LMReturn::Error("请先删除子级分类");
            }
        } else {
            //这里是查询到了，给出提示，不能删除
            return LMReturn::Error("这个分类下有商品，不能删除");
        }
    }

    //产品的添加和修改
    public function ProductFinancialSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }

        try {
            $all = $request->all();
            $type =  $all['type'];
            $product = isset($all['id']) ? Product::find($all['id']) : new Product();
            if ($type == '1') {
                $time_unit = $all['time_unit'] ?? '2'; //// 周期单位   1日、 2月、3年
                $long_time = isset($all['long_time']) ? ($time_unit == 3 ? $all['long_time'] * 12 : $all['long_time']) : '0';
                $time_unit = $time_unit == 3 ? 2 : $time_unit;
                $class_id = $all['class_id'];
                $ceiling =  $all['ceiling'];
                $money =  $all['money'];
                $name =  $all['name'];
                $pay_type =  $all['pay_type'];
                $pay_time_unit = $all['pay_time_unit'] ?? '2'; //// 周期单位   1日、 2月、3年
                $pay_long =  isset($all['pay_long']) ? ($time_unit == 3 ? $all['pay_long'] * 12 : $all['pay_long']) : '0';
                $pay_time_unit = $pay_time_unit == 3 ? 2 : $pay_time_unit;
                $rate =  $all['rate'];
                $results_rate =  $all['results_rate'];
                $year_type = $all['year_type'];
                $sale_time =  $all['sale_time'];
                if (isset($all['tag_list'])) {
                    $tag_str = implode(',', $all['tag_list']);
                } else {
                    $tag_str = null;
                }
                $commission = $all['commission'] ?? '';
                $commission_type = $all['commission_type'] ?? '';
                $state = $all['state'] ?? '1';
                $app_status = $all['app_status'] ?? '1';
                $wx_xcx_status = $all['wx_xcx_status'] ?? '1';
                $pc_status = $all['pc_status'] ?? '1';
                $remark = $all['remark'];
            } else {
                $content =  $all['content'];
                $detail =  $all['detail'];
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误，错误代码PC003', 'PC003');
        }

        try {
            if ($type == '1') {
                $product->time_unit = $time_unit;
                $product->long_time = $long_time;
                $product->class_id = $class_id;
                $product->ceiling = $ceiling;
                $product->money = $money;
                $product->name = $name;
                $product->year_type = $year_type;
                $product->pay_type = $pay_type;
                $product->pay_time_unit = $pay_time_unit;
                $product->pay_long = $pay_long;
                $product->rate = $rate;
                $product->tag = $tag_str;
                $product->results_rate = $results_rate;
                $product->sale_time = $sale_time;
                $product->commission = $commission;
                $product->commission_type = $commission_type;
                $product->state = $state;
                $product->app_status = $app_status;
                $product->wx_xcx_status = $wx_xcx_status;
                $product->pc_status = $pc_status;
                $product->remark = $remark;
            } else {
                $product->content = $content;
                $product->detail = $detail;
            }
            $product->save();
            return LMReturn::Success($product);
        } catch (\Throwable $th) {
            return LMReturn::Error('添加修改出现错误，错误代码PC004+', 'PC004');
        }
    }

    //产品列表
    public function ProductFinancialList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        //设置where条件
        $where = [];
        //如果传递了  根据是展示在售的或者是下架的
        if (isset($all['status'])) {/*小程序传错参数了，处理一下*/
            $all['state'] = $all['status'];
        }
        if (isset($all['state'])) { // 1在售/2下架
            $where[] = ["product.state", $all['state']];
            $state_list = $all['state'] == [1] ? [1] : [2];
        } else {
            $state_list = [1, 2];
        }

        if (isset($all['app_status'])) { //1 展示 2 不展示
            $app_status = $all['app_status'];
            $where[] = ['product.app_status', $app_status];
        }
        if (isset($all['wx_xcx_status'])) {
            $wx_xcx_status = $all['wx_xcx_status'];
            $where[] = ['product.wx_xcx_status', $wx_xcx_status];
        }
        if (isset($all['pc_status'])) {
            $pc_status = $all['pc_status'];
            $where[] = ['product.pc_status', $pc_status];
        }
        if (isset($all['time_unit'])) {
            $time_unit = $all['time_unit'];
            $where[] = ['product.time_unit', $time_unit];
        }
        $pageSize = 10;
        if (isset($all['size'])) {
            $pageSize = $all['size'];
        }
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::where('id', $worker_id)->with('branches')->first();
        if (isset($worker['branches'])) {
            $branch_id = $worker['branches'][0]['id'];
        } else {
            return LMReturn::Success();
        }
        $can_class_list = utils::get_classify($branch_id);
        if (isset($all['class_id'])) {
            if (in_array($all['class_id'], $can_class_list)) {
                $class_id = $all['class_id'];
                $class_list[] = $class_id;
                $classifies = ProductClass::where('pid', $class_id)->get();
                if ($classifies) {
                    foreach ($classifies as $classify) {
                        if (in_array($classify['id'], $can_class_list)) {
                            $class_list[] = $classify['id'];
                        }
                    }
                }
            } else {
                return LMReturn::Error('抱歉，您没有权限查看该类型产品');
            }
        } else {
            $class_list = $can_class_list;
        }
        $product_list = [];
        if (isset($all['product_name'])) {
            $product_id_list = Product::select('id', 'class_id')
                ->where("name", 'like', '%' . $all['product_name'] . '%')
                ->whereIn('state', $state_list)
                ->get();
            if ($product_id_list) {
                foreach ($product_id_list as $product_id) {
                    if (in_array($product_id['class_id'], $can_class_list)) {
                        $product_list[] = $product_id['id'];
                    }
                }
            }
        }

        $info = json_decode(
            json_encode(
                Product::select(
                    "product.id",
                    "product.name as name",
                    "product.long_time",
                    "product.time_unit",
                    "product.rate",
                    "product.money",
                    "product.ceiling",
                    "product.content",
                    "product.detail",
                    "product.sale_time",
                    "product.pay_type",
                    "product.pay_long",
                    "product.pay_time_unit",
                    "product.year_type",
                    "product.results_rate",
                    "product.state",
                    "product.app_status",
                    "product.wx_xcx_status",
                    "product.pc_status",
                    "product.remark",
                    "product.tag as tag_list",
                    "product_class.id as class_id",
                    "product_class.category_name"
                )
                    ->leftjoin("product_class", "product.class_id", "=", "product_class.id")
                    ->where($where)
                    ->when(isset($all['product_name']), function ($query) use ($product_list) {
                        return $query->whereIn('product.id', $product_list);
                    })
                    ->whereIn('class_id', $class_list)
                    ->orderby("product.update_time", "desc")
                    ->paginate($pageSize)
            ),
            true
        );
        //将数字判断成汉字
        foreach ($info['data'] as $key => $value) {
            // 年化方式 1是年化比例 2是固定年化
            if ($value['year_type'] == 1) {
                $info['data'][$key]['year_type'] = '年化比例';
                $info['data'][$key]['year_type_rate'] = $value['results_rate'] . '%';
            } elseif ($value['year_type'] == 2) {
                $info['data'][$key]['year_type'] = '固定年化';
                $info['data'][$key]['year_type_rate'] = ($value['results_rate'] / 10000) . '万元';
            } else {
                $info['data'][$key]['year_type'] = '未知';
                $info['data'][$key]['year_type_rate'] = "设置错误";
            }
            if ($value['tag_list']) {
                $info['data'][$key]['tag_list'] = explode(',', $value['tag_list']);
            } else {
                $info['data'][$key]['tag_list'] = [];
            }
            // 产品周期 1日、 2月、3年
            if ($value['time_unit'] == 1) {
                $info['data'][$key]['product_time'] = $value['long_time'] . '日';
            } elseif ($value['time_unit'] == 2) {
                $info['data'][$key]['product_time'] = $value['long_time'] . '月';
            } elseif ($value['time_unit'] == 3) {
                $info['data'][$key]['product_time'] = $value['long_time'] . '年';
            } else {
                $info['data'][$key]['product_time'] = "设置错误";
            }
            if ($value['long_time'] == '') {
                $info['data'][$key]['product_time'] = '无期限';
            }
            // 付款方式付款方式  2自然月  4到期 5不付款 4自定义
            if ($value['pay_type'] == 5) {
                $info['data'][$key]['product_pay_time'] = '无需支付';
            } else {
                // 付款间隔 1日、 2月、3年
                if ($value['pay_time_unit'] == 1) {
                    $info['data'][$key]['product_pay_time'] = $value['pay_long'] . '日';
                } elseif ($value['pay_time_unit'] == 2) {
                    $info['data'][$key]['product_pay_time'] = $value['pay_long'] . '月';
                } elseif ($value['pay_time_unit'] == 3) {
                    $info['data'][$key]['product_pay_time'] = $value['pay_long'] . '年';
                } else {
                    $info['data'][$key]['product_pay_time'] = "设置错误";
                }
            }
        }

        return LMReturn::Success($info);
    }

    //产品删除(真删除)
    public function ProductFinancialDelete(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // //接收前端传递过来的值
        $all = $request->all();
        //根据传递过来的商品ID去订单表里面进行查询，如果查询到的话就不让删
        $orderinfo = json_decode(Order::where("product_id", $all['id'])->get(), true);
        if (empty($orderinfo)) {
            $res = Product::where("id", $all['id'])->delete();
            return LMReturn::sqlRes($res, '删除成功', '删除失败');
        } else {
            return LMReturn::Error("该产品产生了订单，不能进行删除");
        }
    }

    // 产品类型更新已售和可售金额更新
    public function ProductClassMoney(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $public_class_list = ProductClass::with('products.orders')->get();
            if ($public_class_list) {
                foreach ($public_class_list as $public_class) {
                    $product_class = ProductClass::find($public_class['id']);
                    if ($public_class['max_money'] == 0) {
                        $product_class->after_money = 0;
                        $product_class->surplus_money = 0;
                    } else {
                        $after_money = 0;
                        if (count($public_class['products']) > 0) {
                            foreach ($public_class['products'] as $product) {
                                if (count($product['orders']) > 0) {
                                    foreach ($product['orders'] as $order) {
                                        if ($order['order_status'] == 4 || $order['order_status'] == 6) {
                                            $after_money = $after_money + $order['order_money'];
                                        }
                                    }
                                }
                            }
                        }
                        $max_money = $public_class['max_money'];
                        $can_money = $max_money - $after_money;
                        $product_class->after_money = $after_money;
                        if ($can_money > 0) {
                            $product_class->surplus_money = $can_money;
                        } else {
                            $product_class->surplus_money = 0;
                        }
                    }
                    $product_class->save();
                }
            }
            $system_base = SystemBase::find(1);
            $times = date('Y-m-d H:i:s', time());
            $system_base->product_up_time = $times;
            $system_base->save();
            return LMReturn::Success(['parameter' => $times . '更新']);
        } catch (\Throwable $th) {
            return LMReturn::Error('更新失败');
        }
    }

    // 产品类型更新已售和可售金额更新时间
    public function ProductClassMoneyUpdate(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $system_base = SystemBase::find(1);
        $update_time = $system_base->product_up_time;
        $strs = $update_time . '更新';
        return LMReturn::Success(['parameter' => $strs]);
    }
}
